<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.FileUploadException"%>
<%@page import="java.util.Iterator"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.UUID"%>




<%
    String savePath = this.getServletConfig().getServletContext().getRealPath("");

    savePath = "D:/JAVA/workspace/springuser/web/uploads/";
    File f1 = new File(savePath);
    if (!f1.exists()) {
        f1.mkdirs();
    }
    DiskFileItemFactory fac = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setHeaderEncoding("utf-8");
    
    List fileList = null;
    
    try {
        fileList = upload.parseRequest(request);
    } catch (FileUploadException ex) {
        return;
    }
    
    Iterator<FileItem> it = fileList.iterator();
    String name = "";
    String extName = "";
    while (it.hasNext()) {
        FileItem item = it.next();
        if (!item.isFormField()) {
            name = item.getName();
            long size = item.getSize();
            String type = item.getContentType();
            if (name == null || name.trim().equals("")) {
                continue;
            }
            
            //扩展名格式： 
            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }
            
            File file = null;
            do {
                //生成文件名：
                name = UUID.randomUUID().toString();
                file = new File(savePath + name + extName);
            } while (file.exists());
            File saveFile = new File(savePath + name + extName);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    out.print(name + extName);
%>
